<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useTransactionStore } from '@/stores/transaction'
import { useCategoryStore } from '@/stores/category'
import type { Transaction } from '@/types'
import { ACCOUNT_TYPES, CATEGORY_ICONS } from '@/types'
import dayjs from 'dayjs'

const router = useRouter()
const transactionStore = useTransactionStore()
const categoryStore = useCategoryStore()

const currentMonth = ref(dayjs().format('YYYY-MM'))
const showMonthPicker = ref(false)

// 动态生成年份和月份选择列表
const generateYearMonthOptions = () => {
  const now = dayjs()
  const currentYear = now.year()
  const currentMonthNum = now.month() + 1 // dayjs月份从0开始
  
  // 年份列：从2020年到当前年份
  const startYear = 2020
  const years = []
  for (let year = startYear; year <= currentYear; year++) {
    years.push({
      text: `${year}年`,
      value: year
    })
  }
  
  // 月份列：1-12月
  const months = []
  for (let month = 1; month <= 12; month++) {
    months.push({
      text: `${month}月`,
      value: month
    })
  }
  
  return [years, months]
}

const monthOptions = ref(generateYearMonthOptions())

// 获取当前选中年月的索引
const getDefaultIndexes = () => {
  const now = dayjs()
  const currentYear = now.year()
  const currentMonthNum = now.month() + 1
  
  const yearIndex = monthOptions.value[0].findIndex((item: any) => item.value === currentYear)
  const monthIndex = currentMonthNum - 1
  
  return [yearIndex >= 0 ? yearIndex : 0, monthIndex]
}

const loadData = async () => {
  console.log('🏠 首页：开始加载数据')
  try {
    // 初始化分类
    console.log('🏠 首页：开始加载分类')
    await categoryStore.fetchCategories()
    if (categoryStore.categories.length === 0) {
      console.log('🏠 首页：分类为空，初始化默认分类')
      await categoryStore.initializeCategories()
    }
    console.log(`🏠 首页：分类加载完成，共${categoryStore.categories.length}个分类`)
    
    // 获取当月交易记录
    console.log('🏠 首页：开始加载交易记录')
    await loadMonthData()
    console.log(`🏠 首页：交易记录加载完成，共${transactionStore.transactions.length}条记录`)
    
    console.log('🏠 首页：所有数据加载完成，发送home-data-ready事件')
    // 发送首页数据就绪事件
    window.dispatchEvent(new Event('home-data-ready'))
    console.log('📢 首页：home-data-ready事件已发送')
  } catch (error) {
    console.error('❌ 首页：数据加载失败', error)
    // 即使失败也要通知，避免卡住
    window.dispatchEvent(new Event('home-data-ready'))
    console.log('📢 首页：home-data-ready事件已发送（失败情况）')
  }
}

onMounted(() => {
  console.log('🏠 首页：onMounted被调用')
  
  // 监听数据库就绪事件
  const handleDatabaseReady = () => {
    console.log('🏠 首页：收到database-ready事件，开始加载数据')
    loadData()
  }
  
  // 如果数据库已经就绪，直接加载；否则等待事件
  if ((window as any).databaseReady) {
    console.log('🏠 首页：数据库已就绪，直接加载')
    loadData()
  } else {
    console.log('🏠 首页：等待database-ready事件')
    window.addEventListener('database-ready', handleDatabaseReady, { once: true })
    
    // 超时保护：3秒后强制加载（防止事件丢失）
    setTimeout(() => {
      if (!categoryStore.categories.length && !transactionStore.transactions.length) {
        console.warn('⚠️ 首页：等待超时，强制加载')
        loadData()
      }
    }, 3000)
  }
})

const loadMonthData = async () => {
  await transactionStore.fetchTransactions({
    startDate: dayjs(currentMonth.value).startOf('month').format('YYYY-MM-DD'),
    endDate: dayjs(currentMonth.value).endOf('month').format('YYYY-MM-DD')
  })
}

// 按日期分组交易记录
const groupedTransactions = computed(() => {
  const groups: { [key: string]: Transaction[] } = {}
  
  transactionStore.transactions.forEach(transaction => {
    const dateKey = dayjs(transaction.date).format('YYYY-MM-DD')
    if (!groups[dateKey]) {
      groups[dateKey] = []
    }
    groups[dateKey].push(transaction)
  })
  
  // 转换为数组并排序
  return Object.entries(groups)
    .map(([date, transactions]) => ({
      date,
      transactions,
      totalIncome: transactions.filter(t => t.type === 'income').reduce((sum, t) => sum + t.amount, 0),
      totalExpense: transactions.filter(t => t.type === 'expense').reduce((sum, t) => sum + t.amount, 0)
    }))
    .sort((a, b) => b.date.localeCompare(a.date))
})

// 今日支出
const todayExpense = computed(() => {
  const today = dayjs().format('YYYY-MM-DD')
  const todayGroup = groupedTransactions.value.find(g => g.date === today)
  return todayGroup ? todayGroup.totalExpense : 0
})

const formatAmount = (amount: number) => {
  return amount.toFixed(2)
}

const formatNumber = (num: number) => {
  return num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

const getCategoryInfo = (categoryId: number) => {
  const category = categoryStore.getCategoryById(categoryId)
  if (category) {
    return {
      name: category.name,
      icon: CATEGORY_ICONS[category.icon as keyof typeof CATEGORY_ICONS] || CATEGORY_ICONS.default,
      color: category.color
    }
  }
  return {
    name: '未知分类',
    icon: CATEGORY_ICONS.default,
    color: '#999'
  }
}

// 格式化日期显示
const formatDateDisplay = (date: string) => {
  const d = dayjs(date)
  const today = dayjs()
  const yesterday = dayjs().subtract(1, 'day')
  
  if (d.isSame(today, 'day')) {
    return '今日'
  } else if (d.isSame(yesterday, 'day')) {
    return '昨日'
  } else {
    const weekdays = ['日', '一', '二', '三', '四', '五', '六']
    return `${d.format('MM月DD日')} 周${weekdays[d.day()]}`
  }
}

// 格式化时间
const formatTime = (date: string | Date) => {
  return dayjs(date).format('HH:mm')
}

const onTransactionClick = (transaction: Transaction) => {
  router.push(`/edit/${transaction.id}`)
}

const onMonthConfirm = ({ selectedOptions }: any) => {
  if (selectedOptions && selectedOptions.length === 2) {
    const year = selectedOptions[0].value
    const month = selectedOptions[1].value
    
    // 检查是否选择了未来日期
    const now = dayjs()
    const selectedDate = dayjs(`${year}-${String(month).padStart(2, '0')}-01`)
    
    if (selectedDate.isAfter(now, 'month')) {
      // 如果选择的是未来月份，使用当前月份
      currentMonth.value = now.format('YYYY-MM')
    } else {
      currentMonth.value = `${year}-${String(month).padStart(2, '0')}`
    }
    
    showMonthPicker.value = false
    loadMonthData()
  }
}

const onMonthPickerCancel = () => {
  showMonthPicker.value = false
}

// 当年份改变时，更新月份选项
const onMonthPickerChange = ({ selectedOptions }: any) => {
  if (selectedOptions && selectedOptions.length >= 1) {
    const selectedYear = selectedOptions[0].value
    const now = dayjs()
    const currentYear = now.year()
    const currentMonthNum = now.month() + 1
    
    // 如果选择的是当前年份，月份只能到当前月
    if (selectedYear === currentYear) {
      const months = []
      for (let month = 1; month <= currentMonthNum; month++) {
        months.push({
          text: `${month}月`,
          value: month
        })
      }
      monthOptions.value = [monthOptions.value[0], months]
    } else {
      // 其他年份显示全部12个月
      const months = []
      for (let month = 1; month <= 12; month++) {
        months.push({
          text: `${month}月`,
          value: month
        })
      }
      monthOptions.value = [monthOptions.value[0], months]
    }
  }
}
</script>

<template>
  <div class="home-view">
    <!-- 顶部统计卡片 -->
    <div class="header-card">
      <div class="month-selector" @click="showMonthPicker = true">
        <span>{{ dayjs(currentMonth).format('YYYY年MM月') }}</span>
        <van-icon name="arrow-down" />
      </div>
      
      <div class="expense-info">
        <div class="label">今日支出(元)</div>
        <div class="amount">{{ formatNumber(todayExpense) }}</div>
      </div>
      
      <div class="month-stats">
        <div class="stat-item">
          <div class="label">本月支出(元)</div>
          <div class="value">{{ formatNumber(transactionStore.totalExpense) }}</div>
        </div>
        <div class="stat-item">
          <div class="label">本月收入(元)</div>
          <div class="value">{{ formatNumber(transactionStore.totalIncome) }}</div>
        </div>
      </div>
    </div>

    <!-- 交易记录列表 -->
    <div class="transaction-container">
      <div v-if="transactionStore.loading" class="loading">
        <van-loading />
      </div>
      
      <div v-else-if="groupedTransactions.length === 0" class="empty">
        <van-empty description="暂无交易记录" />
      </div>
      
      <div v-else class="transaction-groups">
        <div 
          v-for="group in groupedTransactions" 
          :key="group.date"
          class="date-group"
        >
          <!-- 日期标题 -->
          <div class="date-header">
            <span class="date-text">{{ formatDateDisplay(group.date) }}</span>
            <div class="date-stats">
              <span class="expense-text">支 {{ formatAmount(group.totalExpense) }}</span>
              <span class="income-text">收 {{ formatAmount(group.totalIncome) }}</span>
            </div>
          </div>
          
          <!-- 该日的交易列表 -->
          <div class="transaction-list">
            <div 
              v-for="transaction in group.transactions" 
              :key="transaction.id"
              class="transaction-item"
              @click="onTransactionClick(transaction)"
            >
              <div class="transaction-icon" :style="{ backgroundColor: getCategoryInfo(transaction.categoryId).color + '20' }">
                <span :style="{ color: getCategoryInfo(transaction.categoryId).color }">
                  {{ getCategoryInfo(transaction.categoryId).icon }}
                </span>
              </div>
              
              <div class="transaction-info">
                <div class="transaction-category">
                  {{ getCategoryInfo(transaction.categoryId).name }}
                </div>
                <div class="transaction-detail">
                  <span class="time">{{ formatTime(transaction.date) }}</span>
                  <span class="separator">|</span>
                  <span class="desc">{{ transaction.description || ACCOUNT_TYPES[transaction.account] }}</span>
                </div>
              </div>
              
              <div class="transaction-amount" :class="transaction.type">
                {{ transaction.type === 'income' ? '+' : '-' }}{{ formatAmount(transaction.amount) }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 月份选择器 -->
    <van-popup 
      v-model:show="showMonthPicker" 
      position="bottom" 
      :style="{ zIndex: 9999 }"
      :overlay-style="{ zIndex: 9998 }"
    >
      <van-picker
        :columns="monthOptions"
        :default-index="getDefaultIndexes()"
        @confirm="onMonthConfirm"
        @cancel="onMonthPickerCancel"
        @change="onMonthPickerChange"
      >
        <template #title>
          <div style="text-align: center; padding: 16px; font-size: 16px; font-weight: 500;">选择年月</div>
        </template>
      </van-picker>
    </van-popup>
  </div>
</template>

<style scoped>
.home-view {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 60px;
  color: #333;
}

.header-card {
  background: linear-gradient(180deg, #FFD7A3 0%, #FFECD0 100%);
  padding: 20px 16px 24px;
  color: #333;
}

:deep(.van-nav-bar) {
  background-color: #fff;
}

:deep(.van-nav-bar__title) {
  color: #333;
}

.month-selector {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 20px;
  cursor: pointer;
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 20px;
  margin-left: auto;
  margin-right: auto;
  width: fit-content;
}

.month-selector span {
  margin-right: 6px;
}

.month-selector:active {
  background: rgba(255, 255, 255, 0.5);
}

.expense-info {
  text-align: center;
  margin-bottom: 20px;
}

.expense-info .label {
  font-size: 14px;
  opacity: 0.7;
  margin-bottom: 8px;
}

.expense-info .amount {
  font-size: 36px;
  font-weight: bold;
}

.month-stats {
  display: flex;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
}

.stat-item .label {
  font-size: 12px;
  opacity: 0.7;
  margin-bottom: 4px;
}

.stat-item .value {
  font-size: 16px;
  font-weight: 500;
}

.transaction-container {
  background: #f5f5f5;
  min-height: calc(100vh - 250px);
}

.loading {
  text-align: center;
  padding: 60px 0;
}

.empty {
  padding: 60px 0;
}

.transaction-groups {
  padding: 12px 0;
}

.date-group {
  margin-bottom: 12px;
}

.date-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f5f5f5;
}

.date-text {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.date-stats {
  font-size: 12px;
  color: #666;
}

.expense-text {
  color: #666;
  margin-right: 12px;
}

.income-text {
  color: #666;
}

.transaction-list {
  background: #fff;
  overflow: hidden;
}

.transaction-item {
  display: flex;
  align-items: center;
  padding: 14px 16px;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  transition: background-color 0.2s;
}

.transaction-item:last-child {
  border-bottom: none;
}

.transaction-item:active {
  background-color: #fafafa;
}

.transaction-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  margin-right: 12px;
  flex-shrink: 0;
}

.transaction-info {
  flex: 1;
  min-width: 0;
}

.transaction-category {
  font-size: 15px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.transaction-detail {
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
}

.transaction-detail .time {
  flex-shrink: 0;
  color: #999;
}

.transaction-detail .separator {
  margin: 0 6px;
  color: #999;
}

.transaction-detail .desc {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #999;
}

.transaction-amount {
  font-size: 16px;
  font-weight: bold;
  flex-shrink: 0;
  margin-left: 12px;
}

.transaction-amount.income {
  color: #FF9800;
}

.transaction-amount.expense {
  color: #333;
}
</style>
